<template>
  <el-card class="box-card">
    <div class="text item">
      <h2>图片上传</h2>
    </div>

    <el-form ref="uploadData" label-width="120px">
      <!-- 上传类型 -->
      <el-form-item label="上传类型">
        <el-radio-group v-model="uploadData.type">
          <el-radio :label="0">原本图片</el-radio>
          <el-radio :label="1">检测效果图片</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 图片上传 -->
      <el-form-item label="上传图片">
        <el-upload
          class="upload-demo"
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          accept="image/*"
          list-type="picture"
        >
          <el-button size="small" type="primary">选择文件</el-button>
        </el-upload>
      </el-form-item>

      <!-- 名字 -->
      <el-form-item label="名字">
        <el-input v-model="uploadData.name" />
      </el-form-item>

      <!-- 描述 -->
      <el-form-item label="描述">
        <el-input v-model="uploadData.description" type="textarea" />
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { uploadimage } from '@/api/image'
export default {
  data() {
    return {
      uploadData: {
        type: 0, // 默认选择普通图片
        name: '',
        description: '',
        image: null // 存储上传的文件
      }
    }
  },
  methods: {
    handleFileChange(image, fileList) {
      this.uploadData.image = image.raw // 存储选择的文件
    },
    submitForm() {
      if (!this.uploadData.image) {
        this.$message.error('请先选择文件')
        return
      }
      // 新建一个表单数据用于把前端的数据传送到后端
      const formData = new FormData()
      formData.append('image', this.uploadData.image)
      formData.append('name', this.uploadData.name)
      formData.append('description', this.uploadData.description)
      formData.append('type', this.uploadData.type)

      console.log('提交的表单数据', formData)
      // 发送上传图片请求
      uploadimage(formData)
        .then(response => {
          // 请求成功的处理
          console.log(response.data)
        })
        .catch(error => {
          // 请求失败的处理
          console.error(error)
        })
    }
  }
}
</script>

<style scoped>
.box-card {
  margin: 20px;
}

.text.item {
  text-align: center;
}
</style>
